<template>
  <div class="popup">
    <header class="app-header">
      <div class="logo">
        <div class="logo-icon">🤖</div>
        <div class="logo-text">
          <h1>智能答题助手</h1>
          <div class="subtitle">AI Quiz Assistant</div>
        </div>
      </div>
    </header>
    
    <main class="app-main">
      <ConfigSection />
      <ControlPanel />
      <StatusDisplay />
    </main>
    
    <footer class="app-footer">
      <div class="status-indicator" :class="connectionClass">
        <span class="status-icon" :class="connectionClass"></span>
        {{ connectionStatus }}
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import ConfigSection from '../components/ConfigSection.vue'
import ControlPanel from '../components/ControlPanel.vue'
import StatusDisplay from '../components/StatusDisplay.vue'

const connectionStatus = ref('正在检查连接...')
const connectionClass = ref('info')

// 统一的消息处理器
const messageHandler = {
  log: (data) => {
    if (data.includes('错误')) {
      connectionClass.value = 'error'
    }
  },
  connection: (data, status) => {
    connectionStatus.value = data
    connectionClass.value = status || 'info'
  },
  requestConfig: () => handleConfigRequest()
}

// 监听来自背景脚本的消息
const messageListener = (message) => {
  try {
    const { type, data, status, from, action } = message
    
    // 根据消息类型分发到对应处理器
    if (type && messageHandler[type]) {
      messageHandler[type](data, status)
    } 
    // 处理来自内容脚本的配置请求
    else if (from === 'content' && action === 'requestConfig') {
      messageHandler.requestConfig()
    }
  } catch (error) {
    console.error('处理消息出错:', error)
    updateConnectionStatus('通信错误', 'error')
  }
}

// 更新连接状态的辅助函数
function updateConnectionStatus(message, status = 'info') {
  connectionStatus.value = message
  connectionClass.value = status
}

onMounted(async () => {
  try {
    // 设置消息监听器
    chrome.runtime.onMessage.addListener(messageListener)
    
    // 加载配置
    await loadConfig()
    
    // 检查内容脚本是否已注入
    await checkContentScript()
  } catch (error) {
    console.error('初始化出错:', error)
    updateConnectionStatus('初始化错误', 'error')
  }
})

onUnmounted(() => {
  // 移除消息监听器
  chrome.runtime.onMessage.removeListener(messageListener)
})

// 检查内容脚本是否已注入当前页面
async function checkContentScript() {
  try {
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true })
    if (!tabs || !tabs[0]) {
      updateConnectionStatus('无法获取当前标签页', 'error')
      return
    }
    
    // 使用Promise包装chrome.tabs.sendMessage以便使用async/await
    const response = await new Promise((resolve) => {
      chrome.tabs.sendMessage(
        tabs[0].id, 
        { action: 'ping' }, 
        (response) => {
          // 检查是否有错误
          const error = chrome.runtime.lastError
          if (error) {
            console.warn('内容脚本通信错误:', error)
            resolve(null)
            return
          }
          resolve(response)
        }
      )
    })
    
    if (!response) {
      // 如果没有响应，尝试注入内容脚本
      await injectContentScript(tabs[0].id)
    } else {
      updateConnectionStatus('已连接', 'success')
    }
  } catch (error) {
    console.error('检查内容脚本出错:', error)
    updateConnectionStatus('通信错误', 'error')
  }
}

// 注入内容脚本
async function injectContentScript(tabId) {
  try {
    // 尝试注入内容脚本
    await chrome.scripting.executeScript({
      target: { tabId },
      files: ['src/content/index.js']
    })
    
    updateConnectionStatus('内容脚本已注入', 'success')
    
    // 重新检查连接
    setTimeout(checkContentScript, 500)
  } catch (error) {
    console.error('注入内容脚本失败:', error)
    updateConnectionStatus('请刷新页面并重试', 'error')
  }
}

// 加载配置
async function loadConfig() {
  return new Promise((resolve) => {
    chrome.storage.sync.get(['appConfig', 'modelConfig'], (result) => {
      if (!result.appConfig || !result.modelConfig) {
        console.warn('未找到配置，将使用默认配置')
      }
      resolve(result)
    })
  })
}

// 处理配置请求
async function handleConfigRequest() {
  const result = await loadConfig()
  
  if (result.appConfig && result.modelConfig) {
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true })
    
    if (tabs && tabs[0]) {
      chrome.tabs.sendMessage(tabs[0].id, {
        action: 'updateConfig',
        data: {
          appConfig: result.appConfig,
          modelConfig: result.modelConfig
        }
      }).catch(error => {
        console.error('发送配置失败:', error)
      })
    }
  }
}
</script>

<style>
.popup {
  width: 360px;
  min-height: 500px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
  position: relative;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #333;
}

.app-header {
  padding: 20px 16px 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  font-size: 24px;
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.logo-text h1 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: #2c3e50;
  line-height: 1.2;
}

.subtitle {
  font-size: 12px;
  color: #7f8c8d;
  margin-top: 2px;
  font-weight: 400;
}

.app-main {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  min-height: 400px;
  overflow-y: auto;
}

.app-footer {
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(255, 255, 255, 0.2);
  text-align: center;
  font-size: 12px;
}

.status-indicator {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.status-icon {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  display: inline-block;
}

.status-indicator.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.status-indicator.success .status-icon {
  background-color: #28a745;
}

.status-indicator.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.status-indicator.error .status-icon {
  background-color: #dc3545;
}

.status-indicator.info {
  background-color: #d1ecf1;
  color: #0c5460;
  border: 1px solid #bee5eb;
}

.status-indicator.info .status-icon {
  background-color: #17a2b8;
}

/* 全局样式优化 */
* {
  box-sizing: border-box;
}

button {
  transition: all 0.2s ease;
}

button:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

input, select, textarea {
  transition: border-color 0.2s ease, box-shadow 0.2s ease;
}

input:focus, select:focus, textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
</style> 